package com.ai.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ai.web.cache.Constants;
import com.ai.web.cache.UserContext;
import com.ai.web.service.BgMenuService;
import com.ai.web.vo.BgMenuV;
import com.ai.web.vo.QueryData;
import com.ai.web.vo.ResultModel;
import com.tiny.persistence.domain.BgMenu;

/**
 * 后台菜单
 * 
 * @ClassName: bgMenuController
 * @Description: TODO
 * @author:
 * @date: 2014年3月24日
 * 
 */
@Controller
@RequestMapping("/bgMenu")
public class BgMenuController extends BaseController {

	private static Logger logger = Logger.getLogger(BgMenuController.class);

	@Autowired
	private BgMenuService bgMenuService;

	@RequestMapping(value = "/list")
	public String list() {

		logger.info("hello......test");
		return "bgMenu/bgMenu_list";
	}

	@RequestMapping(value = "/query", produces = "application/json")
	@ResponseBody
	public QueryData query(@RequestParam HashMap<String, Object> paramMap)
			throws Exception {

		Map<String, Object> conditionMap = buildCondition(paramMap);
		logger.info("---- " + conditionMap);

		QueryData qd = bgMenuService.queryListAndCount(conditionMap);

		return qd;
	}

	@RequestMapping(value = "/topMenu", produces = "application/json")
	@ResponseBody
	public QueryData findFirstLevelMenu(
			@RequestParam HashMap<String, Object> paramMap,
			HttpServletRequest request) throws Exception {

		QueryData qd = new QueryData();
		try {
			UserContext uc = (UserContext) request.getSession().getAttribute(Constants.USER_CONTEXT);
			@SuppressWarnings("rawtypes")
			List list = bgMenuService.findFirstLevelMenuList(uc.getBgUser().getBgRole().getId());
			qd.setTotalCount(list.size());
			qd.setDataList(list);
			qd.setPageSize(100);
			qd.setCurrPage(1);
			qd.build();
		} catch (Exception e1) {
			throw new Exception(e1);
		}
		return qd;
	}

	@RequestMapping(value = "/menuByParentId/{bgMenuId}", produces = "application/json")
	@ResponseBody
	public QueryData findSecondLevelMenu(@PathVariable("bgMenuId") int menuId,
			@RequestParam HashMap<String, Object> paramMap, HttpServletRequest request) throws Exception {

		QueryData qd = new QueryData();
		try {
			UserContext uc = (UserContext) request.getSession().getAttribute(Constants.USER_CONTEXT);
			@SuppressWarnings("rawtypes")
			List list = bgMenuService.findSecondLevelMenuListByMenuId(menuId, uc.getBgUser().getBgRole().getId());
			qd.setTotalCount(list.size());
			qd.setDataList(list);
			qd.setPageSize(100);
			qd.setCurrPage(1);
			qd.build();
		} catch (Exception e1) {
			throw new Exception(e1);
		}
		return qd;
	}

	@RequestMapping(value = "/new")
	public String newbgMenu(Model model) {

		BgMenuV bgMenuV = new BgMenuV();
		model.addAttribute(bgMenuV);

		return "bgMenu/bgMenu_template";
	}

	@RequestMapping(value = "/update/{bgMenuId}")
	public String updatebgMenu(@PathVariable("bgMenuId") int userId, Model model)
			throws Exception {

		BgMenuV bgMenuV = bgMenuService.getBgMenu(userId);
		logger.info("----- getUser:" + bgMenuV);

		if (bgMenuV == null) {
			// exception redirect error page
			// TODO
		}
		model.addAttribute(bgMenuV);

		return "bgMenu/bgMenu_template";
	}

	@RequestMapping(value = "/save", produces = "application/json")
	@ResponseBody
	public ResultModel savebgMenu(BgMenuV bgMenuV) throws Exception {

		logger.info("-----save:" + bgMenuV);
		bgMenuV.setMenuName("菜单一");
		bgMenuV.setActionUrl("urlaction");
		bgMenuV.setParentId(0);
		bgMenuV.setType("item");

		ResultModel rm = bgMenuService.saveBgMenu(bgMenuV);

		return rm;
	}

	@RequestMapping(value = "/delete", produces = "application/json")
	@ResponseBody
	public ResultModel deletebgMenu(@RequestParam String delIds)
			throws Exception {

		System.out.println(delIds);

		List<Integer> userIds = getDeleteIds(delIds);
		ResultModel rm = bgMenuService.deleteBgMenus(userIds);

		return rm;
	}

	@ResponseBody
	@RequestMapping(value = "/menus", method = RequestMethod.GET)
	public List<Map<String, Object>> findFirstLevelMenu(
			HttpServletRequest request) throws Exception {
		UserContext uc = (UserContext) request.getSession().getAttribute(Constants.USER_CONTEXT);
		List<BgMenu> list = bgMenuService.findAllMenuList(uc.getBgUser().getBgRole().getId());
		List<Map<String, Object>> menus = new ArrayList<Map<String, Object>>();
		List<BgMenu> tempList = getTempList(list);
		for (BgMenu menu : list) {
			if (menu.getParentId() == -1) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", menu.getId());
				map.put("name", menu.getMenuName());
				map.put("type", menu.getType());
				map.put("icon", menu.getIcon());
				map.put("actionUrl", menu.getActionUrl());
				tempList.remove(menu);
				if (Constants.MENU_TYPE_FOLDER.equals(menu.getType())) {
					map.put("children",
							getChildren(tempList, menu.getId(),
									new ArrayList<Map<String, Object>>()));
				}
				menus.add(map);
			}
		}
		return menus;
	}

	private List<BgMenu> getTempList(List<BgMenu> list) {
		List<BgMenu> tempList = new ArrayList<BgMenu>();
		for (BgMenu menu : list) {
			tempList.add(menu);
		}
		return tempList;
	}

	private List<Map<String, Object>> getChildren(List<BgMenu> list,
			int menuId, List<Map<String, Object>> children) {
		List<BgMenu> tempList = getTempList(list);
		for (BgMenu menu : list) {
			if (menu.getParentId() == menuId) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", menu.getId());
				map.put("name", menu.getMenuName());
				map.put("type", menu.getType());
				map.put("icon", menu.getIcon());
				map.put("actionUrl", menu.getActionUrl());
				tempList.remove(menu);
				if (Constants.MENU_TYPE_FOLDER.equals(menu.getType())) {
					map.put("children",
							getChildren(tempList, menu.getId(),
									new ArrayList<Map<String, Object>>()));
				}
				children.add(map);
			}
		}
		return children;
	}
}
